package com.yjt.common.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.yjt.common.security.AESCipher;

public class DecryptPropertyPlaceholderConfigurer extends
		PropertyPlaceholderConfigurer {
	private static final String PREFIX_ENCRYPTED = "encrypted|";
	//对称密钥
	private static final String ENCRYPT_STRING = "123456";
	/**
	 * Override the parent class method, decrypting the specified attribute name
	 * corresponds to the value of
	 */
	@Override
	protected String convertProperty(String propertyName, String propertyValue) {
		if (isEncryptPropertyVal(propertyValue)) {
			try {
				return AESCipher.decrypt(propertyValue.substring(PREFIX_ENCRYPTED.length()), ENCRYPT_STRING);
			} catch (Exception e) {
				new RuntimeException("加载配置文件出错");
			}
		} 
		return propertyValue;
	}

	/**
	 * Judge whether the attribute value to decrypt, here I agreed to decrypt
	 * the attribute names begin with encrypt
	 * 
	 * @param propertyName
	 * @return
	 */
	private boolean isEncryptPropertyVal(String propertyName) {
		if (StringUtils.startsWithIgnoreCase(propertyName, PREFIX_ENCRYPTED)) {
			return true;
		} 
		return false;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(AESCipher.encrypt("root", ENCRYPT_STRING));
		System.out.println(AESCipher.encrypt("lzb199145", ENCRYPT_STRING));
	}
}